package com.elinkway.infinitemovies.download;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.CloudDiskBean;
import com.elinkway.infinitemovies.bean.HtmlDataBean;
import com.elinkway.infinitemovies.bean.PlayStatusReporter;
import com.elinkway.infinitemovies.bean.VStreamInfoList;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi.LeTvBitStreamParam;
import com.elinkway.infinitemovies.http.parser.CloudDiskParser;
import com.elinkway.infinitemovies.http.parser.HtmlParser;
import com.elinkway.infinitemovies.http.parser.VStreamInfoListParser;
import com.elinkway.infinitemovies.http.requesttask.ReportPlayStatusTask;
import com.elinkway.infinitemovies.ui.activity.play.PlayDecodeMananger;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UpdateSnifferManager;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.DefinitionManager;
import com.lvideo.http.LVideoHttpConstant;
import com.lvideo.http.LVideoHttpJavaHandler;
import com.lvideo.http.TrustSSLSocketFactory;
import com.lvideo.http.impl.LVideoHttpParameter;

import org.apache.http.HttpStatus;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class DownloadRequestManager {

    private DownloadJob mDownloadJob;
    private WebView mWebView;
    private TestJavaScriptInterface mTestInterface;
    private String mSnifferParamter = "";
    private Handler mHandler;
    private Runnable mRunnable;
    private int loopMaxNum = 20;
    private int num = 0;
    private String mCurrSinffType;
    private String SNIFF_SUCCESS = "success";
    private String mDefaultDefinition = "";
    private String downLoadUrl;
    private String downLoadType;
    private String mCode = "";
    private String mResponseData = "";
    private String allCloudData = "";

    private PlayStatusReporter mPlayStatusReport = new PlayStatusReporter();

    public PlayStatusReporter getmPlayStatusReport() {
        return mPlayStatusReport;
    }
    public DownloadRequestManager() {
        super();
    }

    public DownloadRequestManager(Context context, DownloadJob downLoadJob) {
        super();
        mTestInterface = new TestJavaScriptInterface();
        final Context cotexttemp = context;
        Activity activity = MoviesApplication.getInstance().getActivity();
        if(activity != null){
            activity.runOnUiThread(new Runnable() // 工作线程刷新UI
            { //这部分代码将在UI线程执行，实际上是runOnUiThread post Runnable到UI线程执行了
                @Override
                public void run() {
                    initWebView(cotexttemp);
                }
            });
        }
        mDownloadJob = downLoadJob;
        num = 0;
    }

    public VStreamInfoList getDownloadData(DownloadEntity downloadEntity) {
        LVideoHttpParameter parameter;
//        String url;
        try {
//            url = initUrl(downloadEntity);// 没有问题
            parameter = initUrl(downloadEntity);
//            url = "http://play.chaojishipin.com/sarrs/geturl?splatid=1701&platid=17&playid=2&appfrom=0&unique_id=ddfc6984-b93f-39f6-a2db-d23b2867c049&pl=1000011&key=daade3e6d144a0d29fb6d75f7659b11e&tss=no&vid=6a08bc8b1c8441cc85e105ac289e28f8&appv=1.1.1-debug&gvid=6a08bc8b1c8441cc85e105ac289e28f8&vtype=252022%2C252021%2C252009";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LogUtils.e(Utils.DOWN_TAG, "request lvideo data exception and msg is " + e.getMessage());
            return null;
        }

        mPlayStatusReport = new PlayStatusReporter();
        mPlayStatusReport.setVid(downloadEntity.getLVideoMid());
        String json = getHttpRequest(parameter, downloadEntity);// 有问题（代理层访问url限制）
        mResponseData = json;
        JSONObject resultObj = null;
        if (TextUtils.isEmpty(json))
            LogUtils.e(Utils.DOWN_TAG, "lvideo json null");
        try{
            if (!TextUtils.isEmpty(json)) {
                resultObj = new JSONObject(json);
            }
        }catch (Exception e){

        }
        VStreamInfoList data = null;
        if (resultObj != null) {
            if("503".equals(resultObj.optString("code")) || "211".equals(resultObj.optString("code")) || "212".equals(resultObj.optString("code"))){
                mCode = resultObj.optString("code");
            }
            data = getJsonObject(resultObj.optString("data"));
        }
        mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
        if (null == data){
            LogUtils.e(Utils.DOWN_TAG, "lvideo data null");
            if (LVideoHttpConstant.TIMEOUT_CODE.equals(mCode)) {
                reportPlayState(MoviesConstant.SERVER_DOWNLOAD_NETS_ERROR, "", "");
            } else if("503".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_503, "", "");
            }else if("211".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_211, "", "");
            }else if("212".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_212, "", "");
            }else if(!"200".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_STATE, mCode, "");
            }else{
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_STATE, "", mResponseData);
            }
        }
        return data;
    }

    /**
     * 乐视源
     * @param downloadEntity
     * @return
     * @throws UnsupportedEncodingException
     */
    private LVideoHttpParameter initUrl(DownloadEntity downloadEntity) throws UnsupportedEncodingException {

        Bundle bundle = new Bundle();
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_MMSID, downloadEntity.getLVideoMid());
        String pls = downloadEntity.getCurrClarity();
        if(TextUtils.isEmpty(pls)){
            pls = DefinitionManager.PLS_MP4_800;
        }
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_PLS, pls);
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_CDETYPE, MoviesHttpApi.LeTvBitStreamParam.KEY_CDETYPE_AES);
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_REQUESTTYPE, LeTvBitStreamParam.KEY_DOWNLOAD);
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_VID, downloadEntity.getLVideoMid());

        LVideoHttpParameter<?, ?> httpParameter = MoviesHttpApi.getLVideoStreamParameter(new VStreamInfoListParser(), bundle);
        MoviesHttpApi.addHeaderAndSig(httpParameter);
        String originalStr = httpParameter.getBaseUrl() + httpParameter.encodeUrl();

        LogUtils.e(Utils.DOWN_TAG, "!!!!!!!加密后的字符串!!!!!!" + originalStr);
        return httpParameter;
    }


    private VStreamInfoList getJsonObject(String json) {
        if (!TextUtils.isEmpty(json)) {
            try {
                VStreamInfoListParser infoListParser = new VStreamInfoListParser();
                JSONObject mContent = infoListParser.getData(json);
                VStreamInfoList data = new VStreamInfoListParser().parse(mContent);

                return data;

            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * TODO 频繁请求会失败的原因不是方法有问题，是传入url原因（影视大全代理层请求接口做了频次限制）
     *
     * @param parameter
     * @return
     */
    public String getHttpRequest(LVideoHttpParameter parameter, DownloadEntity downloadEntity) {
        String json = null;
        InputStream is = null;
        mPlayStatusReport.setAction(MoviesConstant.STATE_ACTION_DOWNLOAD);
        mPlayStatusReport.setPorder(downloadEntity.getPorder());
        if("letv".equals(downloadEntity.getSite())){
            mPlayStatusReport.setSubsrc(downloadEntity.getSite() + "305");
        }else{
            mPlayStatusReport.setSubsrc(downloadEntity.getSite());
        }
        mPlayStatusReport.setSrartRequestTime(System.currentTimeMillis());
        mPlayStatusReport.setAid(downloadEntity.getMid());
        try {
            URL u = new URL(parameter.getBaseUrl() + parameter.encodeUrl());
            if(parameter.getBaseUrl() != null && parameter.getBaseUrl().contains("https")){
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(TrustSSLSocketFactory.createKeyManagers(MoviesApplication.getInstance()), new TrustManager[]{new MyTrustManager()}, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
                HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                LVideoHttpJavaHandler.addRequestHead(conn, parameter.getmHeader(), false);
                conn.setInstanceFollowRedirects(true);
                if(HttpStatus.SC_OK != conn.getResponseCode()){
                    mCode = conn.getResponseCode()+"";
                }else{
                    mCode = HttpStatus.SC_OK + "";
                }
                is = conn.getInputStream();
            }else{
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                LVideoHttpJavaHandler.addRequestHead(conn, parameter.getmHeader(), false);
                conn.setInstanceFollowRedirects(true);
                if(HttpStatus.SC_OK != conn.getResponseCode()){
                    mCode = conn.getResponseCode()+"";
                }
                is = conn.getInputStream();
            }
            json = readData(is, "UTF-8");
            LogUtils.e(Utils.DOWN_TAG, "get json sucess");
        }catch (ConnectTimeoutException timeoutException){
            mCode = LVideoHttpConstant.TIMEOUT_CODE;
        }catch (SocketTimeoutException socketTimeoutException){
            mCode = LVideoHttpConstant.TIMEOUT_CODE;
        }catch (Exception e) {
            e.printStackTrace();
            LogUtils.e(Utils.DOWN_TAG, "read data exception and exception is " + e.getMessage());
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                }
        }
        return json;
    }

    private String readData(InputStream inSream, String charsetName) throws Exception {
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        final byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }

        final byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();

        return new String(data, charsetName);
    }

    public HtmlDataBean requestSnifferData(String api, String referer, String sniffType) {
        String json = getSnifferHttpRequest(api, referer);
        HtmlDataBean data = getSnifferJsonObject(json);
        int retryNum = 0;
        while (data == null && retryNum < 2) {
            retryNum++;
            json = getSnifferHttpRequest(api, referer);
            data = getSnifferJsonObject(json);
        }
        if (data == null) { //tuner容灾

        }
        return data;
    }

    public String getSnifferHttpRequest(String url, String referer) {
        String json = null;
        InputStream is = null;

        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            if (!TextUtils.isEmpty(referer)) {
                conn.setRequestProperty(LVideoHttpConstant.REFERER, referer);
            }
            conn.setConnectTimeout(6000);
            conn.setReadTimeout(6000);
            conn.setInstanceFollowRedirects(true);
            is = conn.getInputStream();
            json = readData(is, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                }
        }

        return json;
    }

    private HtmlDataBean getSnifferJsonObject(String json) {
        if (!TextUtils.isEmpty(json)) {
            try {
                HtmlDataBean data = new HtmlParser().initialParse(json);
                return data;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void initWebView(Context activity) {
        mWebView = new WebView(activity);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.clearCache(true);
        String htmlUrl = UpdateSnifferManager.getInstance().getHtmlURL();
//        String htmlUrl = "file:///android_asset/extractor.html";
        LogUtils.e(Utils.DOWN_TAG, "##############htmlUrl is " + htmlUrl);
        mWebView.loadUrl(htmlUrl);
        mWebView.addJavascriptInterface(mTestInterface, "TestJavaScriptInterface");
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(Utils.DOWN_TAG, " url:" + url);
                view.loadUrl(url);// 当打开新链接时，使用当前的 WebView，不会使用系统其他浏览器
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                setIsLoaded(true);
                LogUtils.e(Utils.DOWN_TAG, "  js webview loaded ok");
            }
        });
    }

    boolean isWebLoaded = false;

    void setIsLoaded(boolean isLoad) {
        this.isWebLoaded = isLoad;
    }

    public class TestJavaScriptInterface {
        @JavascriptInterface
        public void startFunction(String result) {
            LogUtils.e(Utils.DOWN_TAG, "xxxxxxxxxxstartFunctionxxxxxxxxxxx " + result);
            if (null != mDownloadJob)
                if (!TextUtils.isEmpty(result)) {
                    mDownloadJob.parseSniffResult(result);
                } else {
                    LogUtils.e(Utils.DOWN_TAG, "!!!!!!!!!!!!js startFunction method called and js sniff result is null");
                    mDownloadJob.handlerOutSiteDownError();
                }
            else
                LogUtils.e(Utils.DOWN_TAG, "xxxxxxxxxxxxxxxxxxxjs startFunction method called and mDownloadJob not construct xxxxxxxxxxxxxxxxxxxxxx");
        }

        @JavascriptInterface
        public String getmSnifferParamter() {
            return mSnifferParamter;
        }
    }

    private String parseSniffResult(String result) {
        try {
            JSONObject obj = new JSONObject(result);
            JSONObject datatObj = obj.optJSONObject("data");
            String state = obj.optString("state");
            JSONObject playObj = datatObj.optJSONObject(mCurrSinffType);
            if (SNIFF_SUCCESS.equalsIgnoreCase(state) && null != playObj
                    && !TextUtils.isEmpty(playObj.toString())) {
                HashMap<String, String> playMap = new HashMap<String, String>();
                PlayerUtils.setPlayMapVaule(playMap, playObj);
                getDefaultDefinition();
                String playUrl = getDefaultPlayUrl(playMap);
//                Type currPlayerType =DownloadInfo.M3U8.equals(mCurrSinffType) ? Type.MOBILE_H264_M3U8 : Type.MOBILE_H264_MP4;
                return playUrl;
            } else {
//                sniffCallBackError();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前默认播放的清晰度
     */
    private void getDefaultDefinition() {
        mDefaultDefinition = PlayerUtils.getPlayDefinition();
        LogUtils.e(Utils.DOWN_TAG, "!!!!当前默认的清晰度为!!!!!" + mDefaultDefinition);
    }

    public String getDefaultPlayUrl(HashMap<String, String> playMap) {
        String playUrl = "";
        if (null != playMap && playMap.size() > 0) {
            playUrl = playMap.get(mDefaultDefinition);
            if (TextUtils.isEmpty(playUrl)) {
                if (PlayerUtils.SMOOTHURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.STANDARDURL;
                    playUrl = playMap.get(mDefaultDefinition);
                } else if (PlayerUtils.STANDARDURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.SMOOTHURL;
                    playUrl = playMap.get(mDefaultDefinition);
                } else if (PlayerUtils.HIGHURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.STANDARDURL;
                    playUrl = playMap.get(mDefaultDefinition);
                    if (TextUtils.isEmpty(playUrl)) {
                        getDefaultPlayUrl(playMap);
                    }
                } else if (PlayerUtils.SUPERURL.equals(mDefaultDefinition)) {
                    mDefaultDefinition = PlayerUtils.HIGHURL;
                    playUrl = playMap.get(mDefaultDefinition);
                    if (TextUtils.isEmpty(playUrl)) {
                        getDefaultPlayUrl(playMap);
                    }
                }
            }
        } else {
            playUrl = "";
        }
        return playUrl;
    }

    public String getmDefaultDefinition() {
        return mDefaultDefinition;
    }

    /**
     * 云盘请求下载url
     */
    public HashMap getCloudDiskDownloadUrl(DownloadEntity downloadEntity) {
        Bundle bundle = new Bundle();
        bundle.putString(LeTvBitStreamParam.KEY_CLOUD_CODE, downloadEntity.getCloudId());
        bundle.putString(LeTvBitStreamParam.KEY_TYPE, PlayDecodeMananger.CLOUD_MP4);
        bundle.putString(LeTvBitStreamParam.KEY_SRC, "nets");
        bundle.putString(LeTvBitStreamParam.KEY_CDETYPE, LeTvBitStreamParam.KEY_CDETYPE_AES);
        bundle.putString(MoviesHttpApi.LeTvBitStreamParam.KEY_REQUESTTYPE, LeTvBitStreamParam.KEY_DOWNLOAD);

        LVideoHttpParameter<?, ?> httpParameter = MoviesHttpApi.getLVideoStreamParameter(new CloudDiskParser(), bundle);
        MoviesHttpApi.addHeaderAndSig(httpParameter);
        String url = httpParameter.getBaseUrl() + httpParameter.encodeUrl();

        LogUtils.e(Utils.DOWN_TAG, "!!!!!!!云盘url!!!!!!" + url);

        mPlayStatusReport = new PlayStatusReporter();
        mPlayStatusReport.setVid(downloadEntity.getCloudId());
        mPlayStatusReport.setmCloudId(downloadEntity.getCloudId());
        String json = getHttpRequest(httpParameter,downloadEntity);
        mResponseData = json;
        if (TextUtils.isEmpty(json))
            LogUtils.e(Utils.DOWN_TAG, "nets json null");
        JSONObject resultObj = null;
        try{
            if (!TextUtils.isEmpty(json)) {
                resultObj = new JSONObject(json);
            }
        } catch (Exception e){

        }
        HashMap<String, String> downloadHashMap = new HashMap<String, String>();
        String downLoadUrl = null;
        String md5 = null;
        String gSize = null;
        allCloudData = "";
        if (resultObj != null) {
            if("503".equals(resultObj.optString("code")) || "211".equals(resultObj.optString("code")) || "212".equals(resultObj.optString("code"))){
                mCode = resultObj.optString("code");
            }
            downLoadUrl = getCloudDiskUrl(resultObj.optString("data"), downloadEntity.getCurrClarity());
             md5 = getCloudDiskMd5(resultObj.optString("data"), downloadEntity.getCurrClarity());
            gSize = getCloudDiskFileSize(resultObj.optString("data"), downloadEntity.getCurrClarity());
        }
        mPlayStatusReport.setEndRequestTime(System.currentTimeMillis());
        if(TextUtils.isEmpty(downLoadUrl)){
            if (LVideoHttpConstant.TIMEOUT_CODE.equals(mCode)) {
                reportPlayState(MoviesConstant.SERVER_DOWNLOAD_NETS_ERROR, "", "");
            } else if("503".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_503, "", "");
            }else if("211".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_211, "", "");
            }else if("212".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_212, "", "");
            }else if(!"200".equals(mCode)){
                reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_STATE, mCode, "");
            }else{
                if(!TextUtils.isEmpty(allCloudData)){
                    reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_STATE, MoviesConstant.SUCCESS_NO_URL, allCloudData);
                }else{
                    reportPlayState(MoviesConstant.GET_DOWNLOADURL_FAIL_STATE, "", mResponseData);
                }
            }
        }
        downloadHashMap.put("downloadUrl", downLoadUrl);
        downloadHashMap.put("md5", md5);
        downloadHashMap.put("gSize", gSize);
        return downloadHashMap;
    }

    private String getCloudDiskUrl(String json,String pls) {
        if (!TextUtils.isEmpty(json)) {
            try {
                CloudDiskParser cloudDiskParser = new CloudDiskParser();
                JSONObject object = cloudDiskParser.getData(json);
                object.put("pls", pls);//下载选择的清晰度
                CloudDiskBean data = new CloudDiskParser().parse(object);
                String cloudPlayUrl = null;
                if (null != data && null != data.getmPlayUrls() && data.getmPlayUrls().size() > 0) {
                    cloudPlayUrl = data.getmPlayUrls().get(0);
                    allCloudData = data.getAllCloudData();
                }
                return cloudPlayUrl;

            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    private String getCloudDiskMd5(String json, String pls) {
        if (!TextUtils.isEmpty(json)) {
            try {
                CloudDiskParser cloudDiskParser = new CloudDiskParser();
                JSONObject object = cloudDiskParser.getData(json);
                object.put("pls", pls);//下载选择的清晰度
                CloudDiskBean data = new CloudDiskParser().parse(object);
                HashMap<String, CloudDiskBean.VideoListObj> videoListObjHashMap = null;
                CloudDiskBean.VideoListObj currentVideoListObj = null;
                String currClarity = data.getCurrClarity();
                if (null != data) {
                    videoListObjHashMap = data.getSupportVideoListObj();
                }

                if (videoListObjHashMap != null && !StringUtil.isEmpty(currClarity)) {
                    currentVideoListObj = videoListObjHashMap.get(currClarity);
                }
                if (currentVideoListObj == null) {
                    return "";
                }
                return currentVideoListObj.md5;

            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return "";
    }

    private String getCloudDiskFileSize(String json,String pls) {
        if (!TextUtils.isEmpty(json)) {
            try {
                CloudDiskParser cloudDiskParser = new CloudDiskParser();
                JSONObject object = cloudDiskParser.getData(json);
                object.put("pls", pls);//下载选择的清晰度
                CloudDiskBean data = new CloudDiskParser().parse(object);
                String gSize = null;
                HashMap<String, CloudDiskBean.VideoListObj> videoListObjHashMap = null;
                CloudDiskBean.VideoListObj currentVideoListObj = null;
                String currClarity = data.getCurrClarity();

                if (null != data) {
                    videoListObjHashMap = data.getSupportVideoListObj();
                }

                if (videoListObjHashMap != null && !StringUtil.isEmpty(currClarity)) {
                    currentVideoListObj = videoListObjHashMap.get(currClarity);
                }
                if (currentVideoListObj == null) {
                    return "";
                }
                return currentVideoListObj.gsize;
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }



    /**
     * 调用js代码执行截流
     *
     * @param sniffParam
     */
    public void excuteJsSniffLogic(final String sniffParam) {
        Activity activity = MoviesApplication.getInstance().getActivity();
        if(activity != null){
            activity.runOnUiThread(new Runnable() // 工作线程刷新UI
            { //这部分代码将在UI线程执行，实际上是runOnUiThread post Runnable到UI线程执行了
                @Override
                public void run() {
                    // 发送消息调用JS代码
                    if(mWebView != null){
                        LogUtils.e(Utils.DOWN_TAG, "!!!!!!!!!!!!!!开始执行劫流逻辑!!!!!!!!!!!!!");
                        mWebView.clearCache(true);
                        LogUtils.e(Utils.DOWN_TAG, "　js send params : " + sniffParam);
                        LogUtils.e(Utils.DOWN_TAG, "wait js excute result");
                        mWebView.loadUrl("javascript:TestJavaScriptInterface.startFunction(dealWithRequest('" + sniffParam + "'));");
                    }
                }
            });
        }
    }
    private class MyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    }

    private class MyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            //
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            //
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
//			return new X509Certificate[0];
            return null;
        }
    }

    private void reportPlayState(String state, String httpcode, String responsedata){
        mPlayStatusReport.setmHttpCode(httpcode);
        mPlayStatusReport.setmResponsedata(responsedata);
        mPlayStatusReport.setState(state);
        PlayStatusReporter playStatus = null;
        try {
            playStatus = mPlayStatusReport.clone();
        } catch (CloneNotSupportedException e) {

        }
        new ReportPlayStatusTask(MoviesApplication.getInstance(), playStatus).start();
    }
}
